<?php

namespace App\Http\Controllers\Setting;

use App\Models\Banner;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class BannerController extends Controller
{
    /** banner列表 */
    public function index(Request $request)
    {
        if($request->isMethod('post')){
            $model = Banner::orderBy('status','asc')->orderBy('sort','asc')->paginate(config('base.limit'));

            return $this->data($model->items(),$model->total());
        }

        return view('setting.banner.index');
    }

    /** banner编辑 */
    public function edit(Request $request)
    {
        $id = $request->get('id');
        if(!empty($id)){
            $model = Banner::find($id);
        }else{
            $model = new Banner();
        }

        if($request->isMethod('post')){
            $data = $request->all();
            /** 基础验证 */
            $validator = $this->validateBanner($data);
            if ($validator->fails()) {
                return $this->fail($validator->errors()->first());
            }

            $model->title   = $data['title'];
            $model->links   = $data['links'];
            $model->img_url = $data['img_url'];
            $model->sort    = $data['sort'];
            if($model->save()){
                return $this->success('保存成功!');
            }
        }
        return view('setting.banner.edit',['model'=>$model]);
    }

    /** banner排序 */
    public function sort(Request $request)
    {
        $data = $request->input();
        $data['data'] = json_decode($data['data']);

        foreach($data['data'] as $key=>$item){
            $data['data'][$key] = (array)$item;
        }

        $sql = updateBatch($data['data'],'banner');

        DB::update(DB::raw($sql));
        return $this->success('保存成功');
    }

    /** banner删除 */
    public function del(Request $request)
    {

        $id = $request->input('id');
        DB::table('banner')->where(['id'=>$id])->delete();
        return $this->success('删除成功!');
    }

    /** 上架/下架 */
    public function status(Request $request)
    {
        $id = $request->input('id');
        $status = $request->input('status');

        Banner::where(['id'=>$id])->update(['status'=>$status]);

        $msg = $status==1?'上架成功':'下架成功';
        return $this->success($msg);
    }

    private function validateBanner($data)
    {
        $validator = Validator::make($data, [
            'title'     => 'required|max:255',
            'img_url'   => 'required|url',
        ], [
            'required'  => ':attribute不得为空',
            'url'       => ':attribute必须为有效的url',
            'max'       => ':attribute不得超过:max字符'
        ], [
            'title'     => 'banner标题',
            'img_url'   => '图片',
        ]);
        return $validator;
    }
}
